package cn.dujc.superkid.activities;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import cn.dujc.core.ui.BaseActivity;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.MyTestMessageResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.configs.Globals;
import cn.dujc.superkid.utils.Base64Utils;
import cn.dujc.superkid.utils.MD5Util;
import cn.dujc.superkid.utils.Preferences;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class InforUserActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = InforUserActivity.class.getName();
    private RegisterResult loginResult;
    private RegisterResult registerResult;
    private ImageView Image_tx;
    private Bitmap head;
    private TextView username;
    //    private TextView usersex;
    private String status;
    private static String path = "/sdcard/myHead/";
    private int sex = 0;

    @Override
    public int getViewId() {
        return R.layout.activity_infor_user;

    }


    @Override
    public void initBasic(Bundle savedInstanceState) {
        setTitle("编辑个人资料");
        SharedPreferences sPreferences = getSharedPreferences("STATUS", MODE_PRIVATE);
        status = sPreferences.getString("sex", "");
        initView();
    }

    public Toolbar initToolbar(ViewGroup parent) {
        final Toolbar toolbar = (Toolbar) LayoutInflater.from(parent.getContext()).inflate(R.layout.toolbar_normal, parent, false);
        toolbar.findViewById(R.id.toolbar_back_id).setOnClickListener(this);
        return toolbar;

    }

    private void initView() {
        loginResult = Preferences.getInstance().getLoginResult(mActivity);
        username = findViewById(R.id.username);
        Image_tx = findViewById(R.id.Image_tx);
//        usersex.setOnClickListener(this);
        Image_tx.setOnClickListener(this);
        findViewById(R.id.info_to_change_name).setOnClickListener(this);
        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);// 转换成drawable
            Image_tx.setImageDrawable(drawable);
        } else {
            /**
             * 如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        username.setText(loginResult.getNicename());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Image_tx:
                showTypeDialog();
                break;
            case R.id.toolbar_back_id:
                registerResult = Preferences.getInstance().getLoginResult(mActivity);
                registerResult.setNicename(username.getText().toString());
                Preferences.getInstance().saveLoginResult(mActivity, registerResult);
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.info_to_change_name:
                startActivity(new Intent(this, ChangeUserNameActivity.class));
                break;
        }
    }

    private void showTypeDialog() {
        String[] items = {"拍摄", "从相册中选取"};
        //显示对话框
        new AlertDialog.Builder(this).setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                    startActivityForResult(intent2, 2);// 采用ForResult打开
                    dialog.dismiss();
                } else {
                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                    //打开文件
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 1);
                }
            }
        }).show();


    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                }

                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                }

                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        head = extras.getParcelable("data");
                        if (head != null) {
                            /**
                             * 上传服务器代码
                             */
                            setPicToView(head);// 保存在SD卡中
                            Image_tx.setImageBitmap(head);// 用ImageButton显示出来
                        }
                    }
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";// 图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
            loadHead(fileName);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void loadHead(String imgPath) {
        String fileNameByTimeStamp =System.currentTimeMillis() + ".jpg";
        File file = new File(imgPath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("app_user_header", fileNameByTimeStamp, requestFile);
        Map<String, Object> params = new HashMap<>();
        params.put("user_id",Integer.parseInt(loginResult.getUid()));
        params.put("time",System.currentTimeMillis()/1000);
        params.put("logincode",loginResult.getLogincode());

        HttpHelper.getUserCenter().memberPortrait(params,body).enqueue(new ResultCallBack<Result<Object>>(this) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                Log.e("head", body.getMsg());
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                Log.e("head", msg);
            }
        });
    }

}

